package com.tencent.wepay;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tencent.wepay.spi.Configurator;
import com.tencent.wepay.spi.WepayRepository;
public class PropertyConfigurator implements Configurator {
	Logger logger=LoggerFactory.getLogger(PropertyConfigurator.class);
	@Override
	public void doConfigure(InputStream inputStream, WepayRepository repository) {
		System.out.println(inputStream);
	}

	@Override
	public void doConfigure(URL url, WepayRepository repository) {
		Properties props = new Properties();
	    logger.debug("Reading configuration from URL " + url);
	    InputStream istream = null;
	    URLConnection uConn = null;
	    try {
	      uConn = url.openConnection();
	      uConn.setUseCaches(false);
	      istream = uConn.getInputStream();
	      props.load(istream);
	    }
	    catch (Exception e) {
	      if (e instanceof InterruptedIOException || e instanceof InterruptedException) {
	          Thread.currentThread().interrupt();
	      }
	      logger.error("Could not read configuration file from URL [" + url
			   + "].", e);
	      logger.error("Ignoring configuration file [" + url +"].");
	      return;
	    }
	    finally {
	        if (istream != null) {
	            try {
	                istream.close();
	            } catch(InterruptedIOException ignore) {
	                Thread.currentThread().interrupt();
	            } catch(IOException ignore) {
	            } catch(RuntimeException ignore) {
	            }
	        }
	    }
	    doConfigure(props, repository);	
	}
	public void doConfigure(Properties props,WepayRepository repository){
		repository.setAppid(props.getProperty("appid"));
		repository.setKey(props.getProperty("key"));
		repository.setMchId(props.getProperty("mchId"));
		repository.setPassword((String) props.getOrDefault("cert.password",repository.getMchId()));
		repository.setPath(props.getProperty("cert.path"));
		repository.setSecret(props.getProperty("secret"));
		repository.setSubMchId(props.getProperty("subMchId"));
		repository.setSubMchId(props.getProperty("notifyUrl"));
	}
  
}
